package mvc.struts.action;

import java.io.IOException;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;

import mvc.struts.form.ActionForm;
import mvc.struts.form.FullForm;
import mvc.struts.form.XmlBean;

public class ActionServlet extends HttpServlet {

	public ActionServlet()
	{
		super();
	}
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 5923913779505909456L;

	/**
	 * 
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
		IOException, ServletException 
	{	
		ServletContext	servletContext;
		
		//	get path
		System.out.println("request.getServletPath() = " + request.getServletPath());
		System.out.println("request.getRequestURI() = " + request.getRequestURI());
		
		String servletPath = request.getServletPath();
		String pathInfo = request.getPathInfo();
		if (StringUtils.length(pathInfo) > 0) {
		    servletPath = servletPath + pathInfo;
		}
		
		String	path = this.getPath(servletPath);
		System.out.println("servletPath = " + servletPath);
		System.out.println("url path = " + path);
		
		if	(path.equals("") || path.equals("/"))
		{
			RequestDispatcher	dis = request.getRequestDispatcher("/webpage/jsp/index.jsp");
			
			System.out.println("RequestDispatcher dis = " + dis.toString());
			
			dis.forward(request, response);	
			
			return;
		}
		
		//	
		Map<String, XmlBean>	map = (Map<String, XmlBean>)this.getServletContext().getAttribute("struts");
				
		XmlBean	bean = map.get(path);
		
		if	(bean != null)
		{
			System.out.println("XmlBean : " + bean);
		}
		
		String	formClass = bean.getFormClass();
		ActionForm	form = FullForm.full(formClass, request);
		
		String	actionType = bean.getActionType();
		Action	action = null;
		
		String	url = "";
		String	forward_url = "";
		
		try
		{
			Class	classZ = Class.forName(actionType);
		
			action = (Action)classZ.newInstance();
		
			url = action.execute(request, response, form, bean.getActionForward());
			
			forward_url = bean.getActionForward().get(url);
			
		}
		catch(Exception ex)
		{
			ex.printStackTrace();
		}
		
		servletContext = request.getServletContext();
		
//		RequestDispatcher	dis = request.getRequestDispatcher(forward_url);
		RequestDispatcher	dis = servletContext.getRequestDispatcher(forward_url);
		dis.forward(request, response);	
	}
	
	/**
	 * 
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
		IOException, ServletException 
	{	
		doGet(request, response);
	}
	
	/**
	 * 
	 * @param servletPath
	 * @return
	 */
	private	String	getPath(String servletPath)
	{
		return	servletPath.split("\\.")[0];
	}
}
